package com.zhuhjay.chat.server.handler;

import com.zhuhjay.chat.message.LoginRequestMessage;
import com.zhuhjay.chat.message.LoginResponseMessage;
import com.zhuhjay.chat.server.service.UserServiceFactory;
import com.zhuhjay.chat.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author ZhuHJay
 * @date 2023/3/7 23:13
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends AbstractRequestMessageHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        boolean login = UserServiceFactory.getUserService().login(username, msg.getPassword());
        LoginResponseMessage response = login ?
                new LoginResponseMessage(true, "登陆成功") :
                new LoginResponseMessage(false, "用户名或密码错误");
        if (response.isSuccess()) {
            // 登录成功后将用户 channel 存储到会话中
            SessionFactory.getSession().bind(ctx.channel(), username);
        }
        ctx.writeAndFlush(response);
    }
}
